package org.wukongcrm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.wukongcrm.domain.entity.Customer;
import org.wukongcrm.domain.model.R;
import org.wukongcrm.service.CustomerService;

import java.util.Date;
import java.util.List;

/**
 * @author ZhongWang
 * @since 2025 03 31:20:23
 */
@RestController
@AllArgsConstructor
@RequestMapping("/customers")
public class CustomerController {

    private final CustomerService customerService;

    @GetMapping
    public R<Page<Customer>> getAllCustomers(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, String conditions) {
        Page<Customer> page = new Page<>(current, size);
        List<Customer> leadsList = customerService.selectCustomer(page, conditions);
        page.setRecords(leadsList);
        return R.success(page);
    }

    @PostMapping
    public R<Customer> addCustomer(@RequestBody Customer customer) {
        customer.setCreateTime(new Date());
        Integer ownerUserId = customer.getOwnerUserId();
        customer.setCreateUserId(ownerUserId);
        customerService.save(customer);
        return R.success(customer);
    }

    @PutMapping
    public R<Customer> updateCustomer(@RequestBody Customer customer) {
        customer.setUpdateTime(new Date());
        customerService.updateById(customer);
        return R.success(customer);
    }

    @DeleteMapping("/{id}")
    public R<String> deleteCustomer(@PathVariable("id") Integer id) {
        customerService.removeById(id);
        return R.success("success");
    }

    @PutMapping("/owner")
    public R updateOwnerUser (Integer ownerUserId, Integer customerNo) {
        return R.success(customerService.updateOwnerUser(ownerUserId, customerNo));
    }

    @PutMapping("/dealStatus")
    public R updateDealStatus (Integer dealStatus, Integer customerNo) {
        Customer customerServiceById = customerService.getById(customerNo);
        if(customerServiceById.getDealStatus() == 1) {
            return R.error("该客户已成交，请勿重复操作！");
        }
        return R.success(customerService.updateDealStatus(dealStatus, customerNo));
    }
}
